# -*- encoding:utf-8 -*-

import threading

__author__ = 'shudong.msd'


class SafeList(object):
    """
        线程安全列表
    """
    __safelist = list()
    __mutex = threading.RLock()

    def append(self, obj):
        self.__mutex.acquire()
        self.__safelist.append(obj)
        self.__mutex.release()

    def insert(self, index, obj):
        self.__mutex.acquire()
        self.__safelist.index(index, obj)
        self.__mutex.release()

    def pop(self):
        self.__mutex.acquire()
        tmp = self.__safelist.pop()
        self.__mutex.release()
        return tmp

    def remove(self,obj):
        self.__mutex.acquire()
        tmp = self.__safelist.remove(obj)
        self.__mutex.release()
        return tmp

    # 慎用，因为坐标一直在变化
    def remove_by_index(self,index):
        self.__mutex.acquire()
        del(self.__safelist[index])
        self.__mutex.release()

    def remove_by_id(self,id):
        for row in self.__safelist:
            if row['id'] == id:
                self.__mutex.acquire()
                self.__safelist.remove(row)
                self.__mutex.release()
                return row

    def get(self, i):
        return self.__safelist[i]

    def set(self, i, obj):
        self.__mutex.acquire()
        self.__safelist[i] = obj
        self.__mutex.release()

    def size(self):
        self.__mutex.acquire()
        tmp = len(self.__safelist)
        self.__mutex.release()
        return tmp

    def __iter__(self):
        return self.__safelist.__iter__()